package model

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"os"
	"time"
)

var db *gorm.DB


func DbInit() {
	config := Config()
	newDb, err := gorm.Open("mysql", fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.Mysql.User, config.Mysql.Password, config.Mysql.Host, config.Mysql.Port, config.Mysql.Db))
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}
	db = newDb
	sqlDb := db.DB()
	sqlDb.SetConnMaxLifetime(time.Minute * 10)
	sqlDb.SetMaxOpenConns(30)
	sqlDb.SetMaxIdleConns(15)

}

func DB() *gorm.DB {
	return db.New()
}

func createTable() {
	DB().Debug().CreateTable(&CoreRole{})
	DB().Debug().CreateTable(&CoreRolePolicy{})
}